package com.situ.staff.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.staff.bean.User;
import com.situ.staff.dao.UserDao;
import com.situ.staff.service.UserService;
import com.situ.staff.utils.MD5Util;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;

	@Override
	public int reg(User user, String repassword) throws Exception {
		if (user.getUsername().length() < 3 || user.getUsername().length() > 16) {
			throw new Exception("账号格式不正确");
		}
		if (user.getPassword().length() < 3 || user.getPassword().length() > 16) {
			throw new Exception("密码格式不正确");
		}
		if (user.getRelname().length() < 1 || user.getRelname().length() > 16) {
			throw new Exception("真实姓名格式不正确");
		}
		if (user.getPhone().length() > 11) {
			throw new Exception("手机格式不正确");
		}
		if (!repassword.equals(user.getPassword())) {

			throw new Exception("输入的俩次不一致");
		}

		// 账号是否可用

		User selectByUsername = userDao.selectByUsername(user.getUsername());
		if (selectByUsername != null) {
			throw new Exception("账号已被注册，不能使用");

		}
		// 密码MD5

		user.setPassword(MD5Util.getMD5(user.getPassword()));
		// 写入数据库

		return userDao.insert(user);

	}

	@Override
	public User login(User user) throws Exception {

		// 验证数据格式
		if (user.getUsername().length() < 3 || user.getUsername().length() > 16) {
			throw new Exception("账号格式不正确");
		}
		if (user.getPassword().length() < 3 || user.getPassword().length() > 16) {
			throw new Exception("密码格式不正确");
		}
		// md5加密
		user.setPassword(MD5Util.getMD5(user.getPassword()));
		// 查询是否存在
		User selectUser = userDao.selectByUsername(user.getUsername());

		if (selectUser == null) {
			throw new Exception("用户不存在");
		}
		// 检验密码是否正确
		if (!(selectUser.getPassword().equals(user.getPassword()))) {
			throw new Exception("密码不正确");
		}
		return selectUser;
	}

	@Override
	public int edit(User user, String newpassword, String repassword) throws Exception {
		// 验证数据格式

		if (user.getPassword().length() < 3 || user.getPassword().length() > 16) {
			throw new Exception("旧密码格式不正确");
		}

		if (newpassword.length() < 3 || newpassword.length() > 16) {
			throw new Exception("新密码格式不正确");
		}
		if (user.getRelname().length() < 1 || user.getRelname().length() > 16) {
			throw new Exception("真实姓名格式不正确");
		}
		if (user.getPhone().length() > 11) {
			throw new Exception("手机格式不正确");
		}
		// 查询旧密码
		User selectUser = userDao.selectById(user.getId());
		System.out.println(selectUser);
		if (!selectUser.getPassword().equals(MD5Util.getMD5(user.getPassword()))) {
			return -1;
		}
		// 新密码和确认密码是否一样
		if (!newpassword.equals(repassword)) {
			return -2;
		}
		// 加密新密码
		user.setPassword(MD5Util.getMD5(newpassword));
		// 修改数据
		return userDao.update(user);
	}

}
